package com.example.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class LeaderSelectorClientA extends LeaderSelectorListenerAdapter implements Closeable {

    public static void main(String[] args) throws IOException {
        CuratorFramework framework = CuratorFrameworkFactory.builder()
                .connectString("192.168.232.130:2181,192.168.232.130:2182,192.168.232.130:2183")
                .sessionTimeoutMs(5000)// 会话超时时间
                .connectionTimeoutMs(5000)// 连接超时时间
                .namespace("gupao") // 隔离名称
                .retryPolicy(new ExponentialBackoffRetry(1000, 3)) // 重试策略
                .build();
        framework.start();

        LeaderSelectorClientA leaderSelectorClient = new LeaderSelectorClientA("ClientA");
        LeaderSelector leaderSelector = new LeaderSelector(framework, "/leader", leaderSelectorClient);
        leaderSelectorClient.setLeaderSelector(leaderSelector);
        leaderSelectorClient.start();

        System.in.read();
    }


    // 表示当前进程
    private String name;
    // Leader 选举的Api
    private LeaderSelector leaderSelector;

    private CountDownLatch countDown = new CountDownLatch(1);

    public LeaderSelectorClientA(String name) {
        this.name = name;
    }

    public void setLeaderSelector(LeaderSelector leaderSelector) {
        this.leaderSelector = leaderSelector;
        //  自动重复参与选举
        leaderSelector.autoRequeue();
    }

    public void start(){

        // 开始竞争 leader
        leaderSelector.start();
    }

    /**
     *  如果进入当前方法，意味着当前的线程获得了锁，获得锁以后这个方法会被回调，
     *  这个方法结束之后，表示释放锁
     * @param curatorFramework
     * @throws Exception
     */
    @Override
    public void takeLeadership(CuratorFramework curatorFramework) throws Exception {

        System.out.println(name + " -> 现在是leader ");
        countDown.await();// 阻塞当前进程防止 leader 丢失
    }


    @Override
    public void close() throws IOException {
        leaderSelector.close();
    }
}
